import { DataSource, DataSourceOptions } from 'typeorm';
import { join } from 'path';
import * as dotenv from 'dotenv';

// 根据环境加载对应的 .env 文件
const envPath = join(process.cwd(), `.${process.env.NODE_ENV || 'dev'}.env`);
dotenv.config({ path: envPath });

export const dataSourceOptions: DataSourceOptions = {
  type: 'mysql',
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT || '3306', 10),
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  entities: [join(__dirname, '../**/*.entity{.ts,.js}')],
  migrations: [join(__dirname, '../migrations/*{.ts,.js}')],
  synchronize: false,
  logging: process.env.NODE_ENV !== 'production',
  charset: 'utf8mb4',
  timezone: '+08:00',
};

const dataSource = new DataSource(dataSourceOptions);
export default dataSource;
